package com.qn.handle;

import cn.hutool.core.util.StrUtil;
import com.qn.auth.SessionManager;
import com.qn.auth.TokenDao;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 验证拦截器
 *
 * @author Qning
 * @date 2022/05/13
 */
public class AuthenticateInterceptor implements HandlerInterceptor {
    @Resource
    private TokenDao tokenDao;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String authToken = SessionManager.getTokenValueNotCut();
        if (StrUtil.isBlank(authToken)) {
            System.out.println("未登录");
            return false;
        }

        // 1.判断请求是否有效
        String key = TokenDao.TOKEN_REDIS_KEY + authToken;
        String redisToken = (String) tokenDao.getObject(key);
        if (redisToken == null || !redisToken.equals(authToken)) {
            System.out.println("无效 token");
            return false;
        }

        // 2.判断是否需要续期
        Long expire = SessionManager.getTokenExpiration(authToken);
        if (expire != null && expire < 10) {
            System.out.println("token 续期");
            SessionManager.renewalToken(redisToken);
        }
        return true;
    }
}
